package com.wf.smartcomm.server.serviceImpl;

import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.wf.smartcomm.server.bean.Praise;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.model.Page;
import com.wf.smartcomm.server.service.PraiseService;
import com.wf.smartcomm.server.util.IdUtils;

/** 
 * @author 38884306@qq.com  
 * @version 创建时间：2015-5-20 下午3:32:57 
 * 
 */
@Service
@Transactional
public class PraiseServiceImpl implements PraiseService {

	@Resource
	private SessionFactory factory;
	
	@Override
	public void save(Praise praise) {
		praise.setObjectId(IdUtils.uuid());
		praise.setCreatedAt(String.valueOf(System.currentTimeMillis()));
		factory.getCurrentSession().persist(praise);
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public void listByUser(User user, Page page) {
		Query query = factory.getCurrentSession().createSQLQuery("select count(*) from Praise where user = :user");
		query.setParameter("user", user);
		Long counts = (Long) query.uniqueResult();
		page.setTotalCount(counts.intValue());
		query = factory.getCurrentSession().createQuery("from Praise praise where praise.user = :user order by praise.createdAt");
		query.setParameter("user", user);
		query.setMaxResults(page.getPageSize());
		query.setFirstResult(page.getBeginIndex());
		page.setDataList(query.list());
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public void list(Page page) {
		Query query = factory.getCurrentSession().createSQLQuery("select count(*) from Praise");
		Long counts = (Long) query.uniqueResult();
		page.setTotalCount(counts.intValue());
		query = factory.getCurrentSession().createQuery("from Praise order by createdAt");
		query.setMaxResults(page.getPageSize());
		query.setFirstResult(page.getBeginIndex());
		page.setDataList(query.list());
	}

}
